﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace BurnSystems.Gpx
{
    /// <summary>
    /// GPX documents contain a metadata header, followed by waypoints, routes, and tracks. 
    /// You can add your own elements to the extensions section of the GPX document. 
    /// </summary>
    public class GpxDocument
    {
        /// <summary>
        /// Stores the node
        /// </summary>
        protected XElement node;

        /// <summary>
        /// Defines the default namespace
        /// </summary>
        public const string XmlNamespace = "http://www.topografix.com/GPX/1/1";

        /// <summary>
        /// Defines the fully qualified namespace
        /// </summary>
        internal const string FullyQualifiedNS = "{" + XmlNamespace + "}";

        /// <summary>
        /// Stores the waypoints of the document
        /// </summary>
        private List<GpxWaypoint> waypoints = new List<GpxWaypoint>();

        /// <summary>
        /// Stores the routes of the document
        /// </summary>
        private List<GpxRoute> routes = new List<GpxRoute>();

        /// <summary>
        /// Stores the tracks of the document
        /// </summary>
        private List<GpxTrack> tracks = new List<GpxTrack>();

        /// <summary>
        /// Gets a list of waypoints
        /// </summary>
        public IList<GpxWaypoint> Waypoints
        {
            get
            {
                return this.node
                    .Elements(GpxDocument.FullyQualifiedNS + "wpt")
                    .Select(x => new GpxWaypoint(x))
                    .ToList()
                    .AsReadOnly();
            }
        }

        /// <summary>
        /// Gets a list of routes
        /// </summary>
        public IList<GpxRoute> Routes
        {
            get
            {
                return this.node
                    .Elements(GpxDocument.FullyQualifiedNS + "rte")
                    .Select(x => new GpxRoute(x))
                    .ToList()
                    .AsReadOnly();
            }
        }

        /// <summary>
        /// Gets a list of tracks
        /// </summary>
        public IList<GpxTrack> Tracks
        {
            get
            {
                return this.node
                    .Elements(GpxDocument.FullyQualifiedNS + "trk")
                    .Select(x => new GpxTrack(x))
                    .ToList()
                    .AsReadOnly();
            }
        }

        /// <summary>
        /// Loads the information about the point by an xelement
        /// </summary>
        /// <param name="element">Element, from which the information will be read</param>
        public void LoadFromXDocument(XDocument document)
        {
            this.node = document.Element(FullyQualifiedNS + "gpx");
        }
    }
}
